{% extends "admin/index.html" %}
{% load i18n %}

{% block breadcrumbs %}
    <div id="breadcrumbs">
      <a href="/">{% trans 'Home' %}</a>{% if title %} &rsaquo; {{ title }}{% endif %}
      &rsaquo; <a href="{% url ecwsp.omr.views.my_tests %}">{% trans 'My Tests' %}</a>
      &rsaquo; <a href="{% url ecwsp.omr.views.edit_test test.id %}">{{ test }}</a>  
      &rsaquo; {{ test }} Questions
    </div>
{% endblock %}

{% block extrahead %}
    {% load adminmedia %}
    <script type="text/javascript" src="/admin/jsi18n/"></script>
    {{ question_form.media }}
    <style type="text/css">
      .content-grid {
        min-width: 800px !important;
      }
      .group h2, .module h2, .group div {
        padding: 1px;
      }
      .question_header input[type="text"]{
        padding: 0px;
        border-style: dotted;
        height: inherit;
        background: transparent;
        width: 35px;
      }
      .row {
        margin: 0px;
      }
      .module:first-child {
        margin-top: 0 !important;
      }
      #content {
        margin: 0px;
      }
    </style>
{% endblock %}

{% block stylesheets %}
  {{ block.super }}
  <style type="text/css">
    tbody th, tbody td {
      border-top: 0px solid white;
      border-bottom: 0px solid #E0E0E0;
    }
    .group ul, .group li {
      list-style-type: inherit;
      margin-left: 6px;
    }
    .group ol {
      margin-left: 6px;
    }
    .group div {
      font-weight: normal;
      padding: 3px 5px;
    }
    .qtable_right {
      float: right;
      width: 130px;
    }
    button.delete-link {
      color: white;
      border: 1px solid #992626;
      background: #BF3030;
      background: -moz-linear-gradient(top, #D93636, #BF3030);
      background: -webkit-gradient(linear, left top, left bottom, from(#D93636), to(#BF3030));
      background: -o-linear-gradient(top, #D93636, #BF3030);
    }
    
    .save_bar {
      border: 0;
      border-top: 1px solid #BDBDBD;
      border-radius: 0;
      border-bottom-left-radius: 5px;
      border-bottom-right-radius: 5px;
      background: #333;
      background: -moz-linear-gradient(top, #444, #333);
      background: -webkit-gradient(linear, left top, left bottom, from(#444), to(#333));
      background: -o-linear-gradient(top, #444, #333);
    }
    form {
      margin-top: -2px;
    }
    
    disabled {
      background: #808080;
    }
    
    .tools a.icon {
      height: 6px;
    }
  </style>
{% endblock %}

{% block javascripts %}
  {{ block.super }}
  <script type="text/javascript" src="/admin/jsi18n/"></script>
  <script type="text/javascript" src="/static/grappelli/js/admin/RelatedObjectLookups.js"></script>
  <script type="text/javascript" src="/static/js/jquery.blockUI.js"></script>
  <script type="text/javascript">
    function clean_ckeditor(question_id) {
      var instances = CKEDITOR.instances;
      re = "id_questionanswers_" + question_id + "-.*-answer";
      instances["id_question_" + question_id + "-question"].destroy();
      $.each(instances, function(key, value) { 
        if ( key.match(re) ) {
          instances[key].destroy();
        }
      });
    }
    
    function dismissQuestionBankPopup(window, question_bank_id) {
      $.post(  
        "ajax_question_bank_to_question/" + question_bank_id + "/",
        function(data){
          $('#new_question_div').before(data);
        }  
      );
      window.close();
    }
    
    function dismissBenchmarkPopup(window, benchmark_id, benchmark_text) {
      $('#id_question_' + foo + '-benchmarks').val($('#id_question_' + foo + '-benchmarks').val() + benchmark_id + '|');
      
      $('#id_question_' + foo + '-benchmarks_on_deck').append('<div id="id_question_' + foo + '-benchmarks_on_deck_' + benchmark_id + '"><span class="iconic" id="kill_id_question_' + foo + '-benchmarks' + benchmark_id + '">X</span> ' + benchmark_text + ' </div>');
      
      window.close();
    }
    
    foo = "";
    function showBenchmarkPopup(page, question_id) {
      foo = question_id;
      return showAddAnotherPopup(page);
    }
    
    function check_correct_answer(question_id) {
      possible = $("#id_question_" + question_id + "-point_value").val();
      
      // Clear green
      $('input')
        .filter(function() {
          return this.id.match("id_questionanswers_" + question_id + "-.*-point_value");
        })
        .removeAttr("style")
      ;
      // Set green for correct answer
      $('input')
        .filter(function() {
          return this.id.match("id_questionanswers_" + question_id + "-.*-point_value");
        })
        .filter(function() { return $(this).val() == possible; })
        .css('background-color', '#a6ffa8')
      ;
    }
    
    function edit_question(id) {
      // Change read only question into editable
      $.post(  
        "ajax_question_form/" + id + "/",
        function(data){
          $("#question_" + id).html(data);
        }  
      );
    }
    
    function cancel_edit(id){
    // cancel changes and bring back read only form.
      var confirmed = confirm("Cancel changes?");
      if ( confirmed ) {
        clean_ckeditor(id);
        if (id == 'new') {
          $("#question_" + id).remove();
        } else {
          $.post(  
            "ajax_read_only_question/" + id + "/",
            function(data){
              $("#question_" + id).html(data);
            }  
          );
        }
      }
    }
    
    function delete_question(id) {
      // Delete selected question completly.
      var confirmed = confirm("Are you sure you want to permanently delete this question?");
      if ( confirmed ) {
        clean_ckeditor(id);
        $.post(  
          "ajax_delete_question/" + id + "/",
          function(data){
            // Remove element only on successful ajax call
            if (data == "SUCCESS") {
              $("#question_" + id).remove();
            }
          }  
        );
      }
    }
    
    function add_question() {
      // Add new question
      if ( $('#question_new').length ) {
        var submit_new = confirm('You must save previous question first. Would you like to save now?');
        if ( submit_new ) {
          $('#question_new').find('#save_question_new').click()
        }
        return false;
      }
      
      $.post(
        "ajax_question_form/new/",
        function(data){
          $('#new_question_div').before(data);
        }  
      );
    }
    
    function save_question(form_id, question_id) {
      // Ajax save a form
      for ( instance in CKEDITOR.instances ) {
        CKEDITOR.instances[instance].updateElement();
      }
      
      $("#" + form_id).find('.answer_div').each( function(i, answer_div) {
        // in the answer div, find the answer span, then find the text area and get it's ID. Use that to find the CKEDITOR instance.
        // The replace br is due to some oddity in firefox where by default there is a br unless clicked on.
        if ( CKEDITOR.instances[$(answer_div).find('.answer_span').find('textarea').attr('id')].getData().replace('<br />\n', '').length <= 0 ) {
          $(answer_div).find('input:checkbox').prop("checked", true);
          $(answer_div).find('input:checkbox').val("on");
          $(answer_div).find('input:checkbox').attr("checked", "checked");
        }
      });
      
      form_data = $("#" + form_id).serialize();
      
      clean_ckeditor(question_id);
      
      $.post(  
        "ajax_question_form/" + question_id + "/",
        form_data,
        function(data){
          if ( question_id == "new" ){
            $('#new_question_div').before(data);
            $('#question_new').remove();
          } else {
            $("#question_" + question_id).html(data);
          }
        }  
      );
    }
    
    function move_question(direction, question_id) {
      var question_div = $('#question_' + question_id);
      if ( direction == "up" ) {
        var prev_div = question_div.prev();
        var question_up_id = question_div.attr('id');
        var question_down_id = prev_div.attr('id');
        question_div.css("position", "relative");
        prev_div.css("position", "relative");
        question_div.animate({top: -prev_div.height()},500);
        prev_div.animate({top: question_div.height()},500, function() {
          setTimeout(function() {
            question_div.css('position', 'static');
            prev_div.css('position', 'static');
            question_div.css('top', '0px');
            prev_div.css('top', '0px');
            question_div.removeAttr("style");
            prev_div.removeAttr("style");
            question_div.insertBefore(prev_div);
          }, 50);
        });
      } else {
        var prev_div = question_div.next();
        var question_up_id = prev_div.attr('id');
        var question_down_id = question_div.attr('id');
        question_div.css("position", "relative");
        prev_div.css("position", "relative");
        question_div.animate({top: prev_div.height()},500);
        prev_div.animate({top: -question_div.height()},500, function() {
          setTimeout(function() {
            question_div.css('position', 'static');
            prev_div.css('position', 'static');
            question_div.css('top', '0px');
            prev_div.css('top', '0px');
            question_div.removeAttr("style");
            prev_div.removeAttr("style");
            prev_div.insertBefore(question_div);
          }, 50);
        });
      }
        
      $.post(  
        "ajax_reorder_question/",
        {'question_up_id': question_up_id, 'question_down_id': question_down_id},
        function(data){
          $.each(data, function(key, value) {
            $('#question_' + key).find('.question_order').html(value);
          });
        },
        "json"
      );

    }
    
    function check_type(question_id) {
      var question_type = $('#id_question_' + question_id + '-type');
      if ( question_type.val() == "True/False" ) {
        $('#question_' + question_id + '_answers_div').hide();
        $('#question_' + question_id + '_is_true_div').show();
      } else {
        $('#question_' + question_id + '_answers_div').show();
        $('#question_' + question_id + '_is_true_div').hide();
      }
    }
    
    function finalize_test() {
      var confirmed = confirm("Are you sure you want to finalize this test?\nYou will no longer be able to make changes to this test.");
      if ( confirmed ) {
        $.blockUI({
          overlayCSS: { backgroundColor: '#00f' },
          message: '<h1>Sending tests to QueXF...please wait. This may take up to a minute. You will be notified in case or errors or thermo-nuclear warfare.</h1>', 
        });
        
        $.post(  
          "ajax_finalize_test/",
          function(data){
            if (data == "SUCCESS") {
              document.location.href = '/omr/test_result/{{ test.id }}';
            } else {
            // Error, let user know they should panic!
              $.blockUI({
                overlayCSS: { backgroundColor: '#ff0009' },
                message: '<h1>Error! Click outside this box to dismiss.</h1>' + data, 
              });
              $('.blockOverlay').attr('title','Click to unblock').click($.unblockUI); 
            }
          }
        );
      }
    }
  </script>
{% endblock %}

{% block content %}
  <h1> Open Metric Recognition </h1>
  
  <h2>{{ test }} Questions </h2>
  {% for question in questions %}
    <div class="group tabular question_div" id="question_{{ question.id }}">
      <div class="row module">
        <div class="row">
          <h2 class="collapse-handler">
            Question <span class="question_order">{{ question.order }}</span>
            <ul class="tools">
              {% if not test.finalized %}
                <li class="open-handler-container"><a href="javascript://" onclick="move_question('down', {{ question.id }})" class="icon open-handler" title="Move Down"></a></li>
                <li class="close-handler-container"><a href="javascript://" onclick="move_question('up', {{ question.id }})" class="icon close-handler" title="Move Up"></a></li>
              {% endif %}
            </ul>
          </h2>
          <table style="width:100%; ">
            <tr>
              <td>
                {{ question.question|safe }}
              </td>
              <td class="qtable_right">
                <div>
                  {{ question.point_value }} Possible Point {{ question.point_value|pluralize }}
                  <br/>
                  {{ question.type }}
                  {% if question.group %} <br/> Group: {{ question.group }} {% endif %}
                  {% for benchmark in question.benchmarks.all %}
                    {% if forloop.first %} <p style="font-weight: bold; padding:0px;"> Benchmarks </p> {% endif %}
                    <p style="padding:0px;">{{ benchmark }}</p>
                  {% endfor %}
                  {% for theme in question.themes.all %}
                    {% if forloop.first %} <p style="font-weight: bold; padding:0px;"> Themes </p> {% endif %}
                    {{ theme }}
                  {% endfor %}
                </div>
              </td>
            </tr>
          </table>
        </div>
      </div>
      <div class="row module">
        {% for answer in question.answer_set.all %}
          <div class="row" {% if answer.point_value == question.point_value %} style="background: #a6ffa8;" {% endif %}>
            <table style="width:99%; ">
              <tr>
                <td>
                  {{ answer.answer|safe }}
                </td>
                <td class="qtable_right">
                  {{ answer.point_value }} Point{{ answer.point_value|pluralize }}
                  {% if answer.error_type %} <br/> Error Type: {{ answer.error_type }} {% endif %}
                </td>
              </tr>
            </table>
          </div>
        {% endfor %}
      </div>
      {% if not test.finalized %}
        <button onclick="edit_question({{ question.id }});">Edit</button>
      {% endif %}
    </div>
  {% endfor %}
  <div id="new_question_div"></div>
  
  {% if not test.finalized %}
    <button onclick="add_question();">Add Question</button>
    <a onclick="return showAddAnotherPopup(this);" href="/omr/question_bank/">
      <button>Add Question from Question Bank</button>
    </a>
  {% endif %}
  
  <br/><br/>
  <div class="module save_bar">
    <a href="download_test" target="_blank"> <button> View Test </button> </a>
    
    <span style="float: right;">
        <button onclick="finalize_test();">Finalize</button>
    </span>
  </div>
  <a href="/sis/preferences?refer={{ request.get_full_path }}">Remember you can change defaults in your preferences</a>
  
{% endblock %}
